<template>
  <!-- 回票申请 -->
  <div class="jeecg-basic-table jeecg-basic-table-form-container">
    <a-form @keyup.enter.native="searchQuery">
      <a-row :gutter="8" type="flex">
        <a-col flex="135px">
          <a-form-item label="部门" :label-col="{ style: { width: '40px' } }" :wrapper-col="{ span: 18 }">
            <JDictSelectTag
              v-model:value="queryParam.ddlxIds"
              mode="multiple"
              dictCode="ddlxType@ddlxUser"
              placeholder="全部"
              :maxTagCount="0"
              :getPopupContainer="(node) => node.parentNode"
              :dropdownStyle="{ width: '120px', overflow: 'auto' }"
              :dropdownMatchSelectWidth="false"
            />
          </a-form-item>
        </a-col>

        <a-col flex="120px">
          <a-form-item label="状态" :label-col="{ style: { width: '40px' } }" >
            <a-select v-model:value="queryParam.sflx" placeholder="全部" :showArrow="false" :allowClear="true">
              <a-select-option value="1">收入</a-select-option>
              <a-select-option value="2">支出</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>

        <a-col flex="340px">
          <a-form-item label="" :label-col="{ style: { width: '70px' } }" :wrapper-col="{ style: { width: '250px' } }">
            <a-select v-model:value="queryParam.sdate" default-value="0" id="today" style="width: 90px; margin-right: 5px" @change="todayChange" >
              <a-select-option value="0">出团日期</a-select-option>
              <a-select-option value="1">收付日期</a-select-option>
            </a-select>
            <a-date-picker
              v-model:value="queryParam.beginDate"
              :disabled-date="disabledStartDate"
              valueFormat="YYYY-MM-DD"
              placeholder=""
              style="width: 110px; padding: 4px"
            /> ~
            <a-date-picker
              v-model:value="queryParam.endDate"
              :disabled-date="disabledEndDate"
              valueFormat="YYYY-MM-DD"
              placeholder=""
              style="width: 110px; padding: 4px"
            />
          </a-form-item>
        </a-col>

        <a-col flex="145px">
          <a-form-item label="操作人" :label-col="{ style: { width: '55px' } }">
            <JDictSelectTag
              v-model:value="queryParam.userIds"
              mode="multiple"
              dictCode="sys_user,realname,id@authUser"
              placeholder="全部"
              :maxTagCount="0"
              :dropdownStyle="{ width: '120px', overflow: 'auto' }"
              :dropdownMatchSelectWidth="false"
              :allowClear="true"
            />
          </a-form-item>
        </a-col>

        <a-col flex="185px">
          <a-form-item label="订单号" :label-col="{ style: { width: '55px' } }">
            <a-input placeholder="" v-model:value="queryParam.orderId" ></a-input>
          </a-form-item>
        </a-col>

        <a-col flex="auto" style="float:right; width:90px; margin-right: 0px;">
          <span style="float: right;overflow: hidden;" class="table-page-search-submitButtons">
            <a-button type="primary" preIcon="ant-design:search" @click="searchQuery" class="mr-10px">查询</a-button>
            <a-button color="success" preIcon="ant-design:plus-outlined" @click="auditALLSelect" >回票登记</a-button>
          </span>
        </a-col>
      </a-row>

      <a-row :gutter="8" type="flex">
        <a-col flex="464px">
          <a-form-item label="采购单位" :label-col="{ style: { width: '66px' } }">
            <Cascader v-model:value="cascader.ids" :options="cascader.options" placeholder="请选择" stringToNumber @change="cooperatorSelect" :show-search="{ filter }"/>
          </a-form-item>
        </a-col>

        <a-col flex="280px">
          <a-form-item label="备注" :label-col="{ style: { width: '65px' } }">
            <a-input placeholder="" v-model:value="queryParam.bz" ></a-input>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </div>

  <!--引用表格 :rowSelection="rowSelection"-->
  <BasicTable @register="registerTable" :loading="loading" :rowSelection="rowSelection"></BasicTable>
  <!-- table区域-end v-auth="'business:delete'"-->

  <BackAccountAdd @register="registerBackAccountAdd" @success="searchQuery"></BackAccountAdd>
</template>

<script lang="ts" setup name="invoiceList-backAccountList">
import { ref, computed, unref, reactive, toRaw, watch, onMounted, nextTick } from "vue";
import { BasicColumn, BasicTable } from "/@/components/Table";
import { useModal } from "/@/components/Modal";
import { useListPage } from "/@/hooks/system/useListPage";
import { momentSearchQueryDate } from "/@/utils/dateUtil";
import { render } from "/@/utils/common/renderUtils";
import { backAccountList } from "/@/views/full/invoice/types/invoice.api";
import { useMessage } from "/@/hooks/web/useMessage";
import { Cascader } from 'ant-design-vue';
import { coopSelect } from "/@/views/full/business/business.api";
import moment from 'dayjs'
import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
import BackAccountAdd from './modules/backAccountAdd.vue'

//初始化 -------------------------------------------------------------
const { createMessage: $message } = useMessage();
//定义查询表单，查询条件
const queryParam = reactive<any>({
  ddlxIds: [],
  sflx: '2',
  beginDate : momentSearchQueryDate('sub', 60),
  endDate: momentSearchQueryDate('add', 0),
});

//限制查询日期，开始日期不能大于结束日期
function disabledStartDate(beginDate) {
  const endDate = queryParam.endDate;
  if (!beginDate || !endDate) {
    return false;
  }
  return beginDate.valueOf() > moment(endDate).valueOf()
}

function disabledEndDate(endDate) {
  const beginDate = queryParam.beginDate;
  if (!endDate || !beginDate) {
    return false;
  }
  return moment(beginDate).valueOf() > endDate.valueOf();
}
//初始化 -------------------------------------------------------------

function searchQuery() {
  setSelectedRowKeys([]);
  setProps({searchInfo:toRaw(queryParam)});
  reload()
}

function searchReset() {
  Object.assign(queryParam, {ddlxIds: '', ddzt: '', ywlx: ''});
}

function handleSummary(tableData: Recordable[]) {
  const res = getRawDataSource()
  redoHeight();
  if (res) {
    return getRawDataSource().summary;
  } else {
    return [];
  }
}

function todayChange() {
  if (queryParam.sdate == '1') {
    queryParam.shbj = '1'
  } else {
    queryParam.shbj = '0'
  }
}

const dwmc = ({ text, record }) => {
  if (record.sflx == "1") {
    text = record.customerPathName
  } else {
    text = record.cooperatorPathName
  }
  if (!text) {
    return "";
  } else {
    return text;
  }
};

//订单列表 - 表头
const columns: BasicColumn[] = [
  { title: "部门", align: "center", dataIndex: "ddlx", width: 65, customRender:({text}) => render.renderDict(text, 'ddlxType') },
  { title: "订单号", align: "center", dataIndex: "orderId", width: 100, className:"text-red-500" },
  { title: "收付单位", align: "left", dataIndex: "dwmc", width: 210, customRender: dwmc, ellipsis: true },
  { title: "收入", align: "right", dataIndex: "skje", width: 80, className:"text-red-500" },
  { title: "支出", align: "right", dataIndex: "fkje", width: 80, className:"text-green-500" },
  { title: "收付时间", align: "center", dataIndex: "sfsj", format: "date|YYYY-MM-DD", width: 90 },
  { title: "银行", align: "left", dataIndex: "djm", width: 80 },
  { title: "备注", align: "left", dataIndex: "bz", width: 250 },
  { title: "操作人", align: "center", dataIndex: "lrr", width: 60 },
]

// 列表页面公共参数、方法
const loading     = ref<boolean>(false);
const dataSource  = ref<any[]>([]);
const summaryData = ref<any[]>([]);
const {prefixCls, tableContext, onExportXls, onImportXls} = useListPage({
  designScope: 'invoiceBackAccountList',
  tableProps: {
    rowKey: 'id',
    api: backAccountList,
    columns: columns,
    showIndexColumn: false,    //行号
    clickToRowSelect: true,    //点击选择
    showActionColumn: false,
    showTableSetting: false,
    useSearchForm: false,
    showSummary: false,
    beforeFetch: (params) => Object.assign(params, unref(queryParam)),
  },
})

//注册table数据
const [registerTable, {reload, setProps, getRawDataSource, setSelectedRowKeys, redoHeight}, {rowSelection, selectedRowKeys, selectedRows}] = tableContext

//新增订单
const [registerBusinessAdd, {openModal: openBusinessAdd}] = useModal();
/**
 * 新增事件
 */
function handleCreate() {
  openBusinessAdd(true, { isUpdate: false, });
}

/**
 * order 订单新增后回调函数,自动弹出订单编辑窗口
 * @param businessId
 */
function handleSuccess(businessId) {
  openBusinessOrder(true, businessId);
  reload();
}

//详细订单
const [registerBusinessOrder, {openModal: openBusinessOrder}] = useModal();
//双击行
function handleDblclick(record) {
  openBusinessOrder(true, record.id);
}

//单击行
let selectRows = reactive<any>({id: '', username: ''});
function handleClick(record) {
  selectRows.id = record.id
  selectRows.username = record.username
}

function rowClassName(record, index) {
  return record.id === selectRows.id ? 'row-selected' : '';
}

/**
 * 新增事件
 */
async function handleDelete() {
  if (!selectRows || selectRows.length == 0) {
    alert('请选择数据。');
    return;
  }

  //await businessDelete({id: selectRows.id}, reload)
}

// 开票申请 - 组件 -------------------------
const [registerBackAccountAdd, { openModal: backAccountAdd }] = useModal();
function auditALLSelect(record) {
  //1、获取被选中的行信息
  let rows = unref(selectedRows)
  if (rows.length <= 0) {
    $message.warning("请选择") //请勾选不能为空！
    return false
  }

  //2、判断选中的单位是否是同一家
  var pId = [], ids = ''
  for (var i = 0; i < rows.length; i++) {
    pId.push(rows[i].coopId)
    if (i == 0) {
      ids = rows[i].id;
    } else {
      ids = ids + "," + rows[i].id;
    }
  }
  if (pId.length > 0) {
    pId = pId.sort()
    for (var i = 0; i < pId.length - 1; i++) {
      if (pId[i] != pId[i + 1]) {
        $message.warning('操作失败：请选择同一家供应商！')
        return false
      }
    }
  }

  //console.info(selectedRows);
  backAccountAdd(true, { ids });
}

const cascader = reactive<any>({
  ids: [],
  options: []
});

function cooperatorSelect(value) {
  //console.info("coopOptions", value, cascader.ids)
  if (!value && value.length < 3) {
    return false
  }
  queryParam.coopId = value[2];
}

const filter = (inputValue: string, path) => {
  return path.some(option => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1);
}

/**
 * 收支项目 注册弹出编辑窗口
 * 作者：qdl
 * 日期：2022-07-04
 */
const [registerAccount, { openModal: accountModal }] = useModal();

//收支项目 - 添加
function handleAccountAdd() {
  accountModal(true, {id: 1});
}


onMounted(async () => {
  await nextTick()
  let res = await coopSelect()
  Object.assign(cascader.options, res)
});

</script>
<style lang="less" scoped>

</style>
